<!--
 * @Author: wangyage wangyage@zhejianglab.com
 * @Date: 2022-08-04 14:35:02
 * @LastEditors: wangyage wangyage@zhejianglab.com
 * @LastEditTime: 2022-10-10 17:49:38
 * @FilePath: \aiworks\frontend\src\components\knowledge-gis\viewModal.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <a-modal
    :width="880"
    :title="title"
    :visible="visible"
    :mask-closable="true"
    :destroy-on-close="true"
    :get-container="getContainer"
    @cancel="handleCancel"
  >
    <div class="modal-body">
      <template>
        <pageTableVue
          v-if="type === 'table'"
          :is-sortable="true"
          :page-disabled="false"
          :config="gridItem"
          class="option-media"
          @pagechange="(pageConfig) => onTablePageChange(pageConfig)"
          @sortchange="
            (sortData) => {
              onTableSortchange(sortData)
            }
          "
        >
        </pageTableVue>
        <template v-else-if="type === 'img'">
          <img :src="gridItem.attrValue" alt="pic" class="option-media" />
        </template>
        <template v-else-if="type === 'graph'">
          <simple-k-graph-vis
            :id="id"
            :raw-data="gridItem.attrValue"
            :query-select-id="`graph${Math.random().toString(36).slice(-8)}`"
            :container-width="900"
          />
        </template>
        <template v-else>
          <Chart
            v-if="gridItem.widgetId"
            class="chart-design"
            :config="gridItem.chartOptions"
            :chart-type="type"
            @chartinit="
              (instance) => {
                onChartInstanceInit(instance)
              }
            "
            @chartevent="
              (data) => {
                onChartEvent(data, gridItem)
              }
            "
          >
          </Chart>
        </template>
      </template>
    </div>
    <template #footer>
      <a-button type="primary" @click="handleCancel">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import pageTableVue from '@/components/pageTable/pageTable.vue'
import Chart from '@/components/chart/chart.vue'
import SimpleKGraphVis from '@/components/knowledge-vis/SimpleKGraphVis.vue'
import { cloneDeep, debounce } from 'lodash'
import { getWidgetData } from '@/api/widget'
import { parseGetDataResult } from '@/components/common/VisualizationDashboard/util'

interface KeyValue {
  [key: string]: any
}

@Component({
  components: {
    pageTableVue,
    Chart,
    SimpleKGraphVis,
  },
})
export default class ModalVisualization extends Vue {
  @Prop({ default: false }) visible!: boolean
  @Prop({ default: null }) config!: Object
  @Prop({ default: '' }) type!: String
  @Prop({ default: '' }) title!: String
  @Prop() id: any

  public gridItem: any = {}
  //  图表选中的维度记录
  public selectedDimension: string[] = []

  @Watch('config', { deep: true })
  watchConfig(newValue: any) {
    this.gridItem =
      this.type.toLocaleLowerCase().indexOf('chart') > 0
        ? {
            ...newValue,
            chartOptions: {
              ...newValue.chartOptions,
              size: [800, 450],
              title: '',
            },
          }
        : newValue
  }
  /**
   * 表格翻页
   * @param pageConfig
   */
  onTablePageChange(pageConfig: { pageNumber: number; pageSize: number }) {
    this.$set(this.gridItem?.chartOptions, 'curPage', pageConfig.pageNumber)
    this.$set(this.gridItem?.chartOptions, 'pageSize', pageConfig.pageSize)
    this.getTableData(this.gridItem)
  }

  /**
   * 排序
   */
  private onTableSortchange(sortData: { key: string; sort: 'desc' | 'asc' }) {
    if (sortData.key) {
      this.$set(this.gridItem?.chartOptions, 'sortCol', [
        { name: sortData.key, sort: sortData.sort },
      ])
      this.getTableData(this.gridItem)
    }
  }

  /**
   * 获取table data
   * @param gridItem
   */
  getTableData(gridItem: any) {
    const parameters: any = {
      data: {
        tableName: gridItem.attrValue, //  replace attr id with tableName
        type: 'dataset',
        tableJson: {
          curPage: gridItem.chartOptions?.curPage ?? 1,
          pageSize: gridItem.chartOptions?.pageSize ?? 50,
          name: '_record_id_',
          filters: [],
          sortCol: gridItem.chartOptions?.sortCol ?? [],
        },
      },
    }
    this.$set(gridItem, 'isLoading', true)
    getWidgetData(parameters)
      .then((response: any) => {
        if ([100, 1106].includes(response.data.code)) {
          const { result } = response.data
          const gridItemClone = cloneDeep(gridItem)
          const { chartOptions } = gridItemClone
          this.$set(this.gridItem, 'chartOptions', {
            ...chartOptions,
            columns: result.columns.map((column: any) => {
              return column.name
            }),
            curPage: result?.page?.curPage || 0,
            totalElements: response.data.result?.page?.totalElements || 0,
            pageSize: result?.page?.pageSize || 50,
            value: result ? parseGetDataResult(result) : [],
            totalPages: result?.page?.totalPages,
          })
          this.$set(gridItem, 'isLoading', false)
        } else {
          this.$message.error(response.data.message)
        }
      })
      .catch(() => {
        this.$set(gridItem, 'isLoading', false)
      })
  }

  /**
   * chart触发的事件
   */
  onChartInstanceInit(chartInstance: any) {
    console.log('viewModal instance:', chartInstance)
  }
  public onChartEvent = debounce((data: any, item: any) => {
    this._onChartEvent(data, item)
  }, 300)
  private _onChartEvent(data: any, option: any) {
    const item = option
    let clickedName: any
    switch (data.name) {
      case 'selectedChange':
      case 'graphNodeClick': // graph node 点击
        // const clickedName = data.event.data.data[item.chartOptions.labelKey]
        console.log(
          data.event.data.data[item.chartOptions.labelKey],
          'okokok',
          item
        )
        clickedName = data.event.data.data[item.chartOptions.labelKey]
        //  只允许有一个选中的维度
        if (this.selectedDimension.includes(clickedName)) {
          this.selectedDimension.pop()
        } else if (item.interactActive.turnOn) {
          this.selectedDimension.push(clickedName)
        }

        break
      default:
        break
    }
  }
  /**
   * 关闭对话框
   */
  public handleCancel() {
    this.$emit('ok')
  }
  /**
   * 将modal挂载到根节点app上，可以应用app的基础样式
   */
  public getContainer() {
    return document.querySelector('.app') as HTMLElement
  }
}
</script>
<style lang="less">
:root {
  --title-color: #373b52;
  --component-bg-color: #fff;
  --component-bg-color-tspt: #fff;
  --component-bg-color-oneop: #fff;
  --component-border-color: #e9e9e9;
  --controller-label: #373b52;
  --controller-input-border: #e9e9e9;
  --controller-innput-arrow: #5d637e;
  --controller-slider-rail: rgba(0, 0, 0, 0.08);
  --controller-palceholder: rgba(0, 0, 0, 0.25);
  --table-th: rgb(250, 250, 250, 0.4);
  --table-tr: rgb(255, 255, 255, 0.7);
  --table-pag-active-num: #6973ff;
  --table-pag-num: #5d637e;
  --table-row-hover: #eff0fe;
  --table-border: rgba(217, 217, 217, 0.4);
  --content-box-bg: rgba(235, 234, 239, 1);
  --tooltip-bg: rgb(255, 255, 255);
}
</style>
<style lang="less" scoped>
/deep/ .ant-modal-body {
  padding: 20px;
}

.modal-body {
  background-color: #fff;
  display: flex;
  height: 462px;
  justify-content: center;
}

/deep/ .chart-title {
  color: #5d637e;
  font-size: 14px;
  font-weight: 500;
  height: 38px;
  line-height: 38px;
}
</style>
